<template>
  <el-card class="chart-card">
    <template #header>
      <div class="card-header">
        <span>供应商报价对比</span>
        <el-radio-group v-model="chartTypeValue" size="small">
          <el-radio-button value="bar">柱状图</el-radio-button>
          <el-radio-button value="line">折线图</el-radio-button>
        </el-radio-group>
      </div>
    </template>
    <div ref="chartContainer" class="chart-container" style="height:350px;"></div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ChartResizer } from '../../utils/chartResize'

// 定义类型
interface Supplier {
  id: string;
  name: string;
  level: string;
}

interface SupplierData {
  price?: number;
  deliveryDays?: number;
  rating?: number;
}

interface MaterialItem {
  materialCode: string;
  materialName: string;
  specification: string;
  unit: string;
  quantity: number;
  suppliers: SupplierData[];
  recommendation: string;
}

// 定义props
const props = defineProps<{
  chartType: string;
  tableData: MaterialItem[];
  suppliers: Supplier[];
}>()

// 定义emit
const emit = defineEmits(['update:chartType', 'chart-ready'])

// 保持内部状态与外部同步
const chartTypeValue = ref(props.chartType)

// 监听内部状态变化并通知父组件
watch(chartTypeValue, (newValue) => {
  emit('update:chartType', newValue)
  updateChart()
})

// 监听外部属性变化
watch(() => props.chartType, (newValue) => {
  chartTypeValue.value = newValue
})

watch(() => props.tableData, () => {
  updateChart()
}, { deep: true })

// 图表实例
let chart: echarts.ECharts | null = null
const chartContainer = ref<HTMLElement | null>(null)

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return
  
  // 改用递归方式尝试初始化，设置最大重试次数
  tryInitChart(1, 10) // 从第1次开始，最多尝试10次
}

// 尝试初始化图表，使用计数器和最大重试次数
const tryInitChart = (attempt: number, maxRetries: number) => {
  if (!chartContainer.value) return
  
  // 检查容器尺寸
  const rect = chartContainer.value.getBoundingClientRect()
  console.log(`PriceComparisonChart容器尺寸(尝试${attempt}/${maxRetries}):`, rect.width, rect.height)
  
  if (rect.width <= 5 || rect.height <= 5) {
    if (attempt < maxRetries) {
      console.warn(`PriceComparisonChart容器尺寸无效, 延迟重试 ${attempt}/${maxRetries}`)
      // 延迟时间随着重试次数增加
      const delay = Math.min(200 * attempt, 1000) // 最长延迟1秒
      setTimeout(() => tryInitChart(attempt + 1, maxRetries), delay)
    } else {
      // 最大尝试次数后强制初始化
      console.warn('达到最大重试次数，强制初始化图表')
      forceInitChart()
    }
    return
  }
  
  // 正常初始化
  initChartInstance()
}

// 强制初始化图表实例，即使容器尺寸不理想
const forceInitChart = () => {
  if (!chartContainer.value) return
  
  // 确保容器有最小尺寸
  chartContainer.value.style.height = '350px'
  chartContainer.value.style.width = '100%'
  
  console.log('PriceComparisonChart强制初始化图表')
  initChartInstance()
}

// 实际初始化图表实例的共用方法
const initChartInstance = () => {
  if (!chartContainer.value) return
  
  // 如果已经初始化过，先销毁
  if (chart) {
    chart.dispose()
  }
  
  console.log('PriceComparisonChart开始初始化图表')
  // 初始化图表
  chart = echarts.init(chartContainer.value)
  
  // 注册到ChartResizer
  ChartResizer.getInstance().register('priceComparisonChart', chart, chartContainer.value)
  
  // 更新图表
  updateChart()
  
  // 通知父组件图表已就绪
  emit('chart-ready', 'priceComparisonChart')
}

// 更新图表
const updateChart = () => {
  if (!chart) return
  
  // 准备数据
  const materials = props.tableData.map(item => item.materialName)
  const seriesData = props.suppliers.map((supplier, index) => {
    return {
      name: supplier.name,
      type: chartTypeValue.value,
      data: props.tableData.map(item => item.suppliers[index]?.price || 0)
    }
  })
  
  // 获取容器宽度以设置响应式配置
  const containerWidth = chart.getWidth()
  const isSmallScreen = containerWidth < 500
  
  // 设置图表配置
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: chartTypeValue.value === 'bar' ? 'shadow' : 'line'
      },
      formatter: function(params: any[]) {
        let tooltip = `${params[0].name}<br/>`
        params.forEach((param: any) => {
          tooltip += `${param.seriesName}: ${param.value} 元<br/>`
        })
        return tooltip
      }
    },
    legend: {
      data: props.suppliers.map(supplier => supplier.name),
      type: isSmallScreen ? 'scroll' : 'plain',
      textStyle: {
        fontSize: isSmallScreen ? 10 : 12
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: materials,
      axisLabel: {
        interval: isSmallScreen ? 'auto' : 0,
        rotate: isSmallScreen ? 30 : 0,
        fontSize: isSmallScreen ? 10 : 12
      }
    },
    yAxis: {
      type: 'value',
      name: '价格(元)',
      nameTextStyle: {
        fontSize: isSmallScreen ? 10 : 12
      },
      axisLabel: {
        fontSize: isSmallScreen ? 10 : 12
      }
    },
    series: seriesData
  }
  
  chart.setOption(option)
}

// 组件挂载
onMounted(() => {
  // 确保在下一个渲染周期执行，并且使用更长的延时以确保DOM完全渲染
  setTimeout(() => {
    initChart()
  }, 500)
  
  // 监听窗口大小变化，重新渲染图表
  window.addEventListener('resize', handleResize)
})

// 处理窗口大小变化
const handleResize = () => {
  if (chart) {
    chart.resize()
  }
}

// 组件卸载前清理资源
onBeforeUnmount(() => {
  if (chart) {
    ChartResizer.getInstance().unregister('priceComparisonChart')
    chart.dispose()
  }
  
  // 移除事件监听器
  window.removeEventListener('resize', handleResize)
})
</script>

<script lang="ts">
export default {
  name: 'PriceComparisonChart'
}
</script>

<style scoped>
.chart-card {
  margin-bottom: 20px;
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-container {
  height: 350px;
  width: 100%;
  position: relative;
  display: block;
}

/* 响应式布局 */
@media (max-width: 1200px) {
  .chart-container {
    height: 300px;
  }
}

@media (max-width: 768px) {
  .chart-container {
    height: 250px;
  }
}

@media (max-width: 480px) {
  .chart-container {
    height: 200px;
  }
}
</style> 